using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using MalwareMultiScan.Api.Attributes;
using MalwareMultiScan.Api.Data.Models;
using MalwareMultiScan.Api.Services.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace MalwareMultiScan.Api.Controllers
{
    /// <summary>
    /// Queue controller.
    /// </summary>
    [ApiController]
    [Route("api/queue")]
    [Produces("application/json")]
    public class QueueController : Controller
    {
        private readonly IScanResultService _scanResultService;

        /// <summary>
        /// Initialize queue controller.
        /// </summary>
        /// <param name="scanResultService">Scan result service.</param>
        public QueueController(IScanResultService scanResultService)
        {
            _scanResultService = scanResultService;
        }

        /// <summary>
        /// Queue file for scanning.
        /// </summary>
        /// <param name="file">File from form data.</param>
        [HttpPost("file")]
        [ProducesResponseType(typeof(ScanResult), StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> ScanFile(
            [Required] [MaxFileSize] IFormFile file)
        {
            var result = await _scanResultService.CreateScanResult();

            string storedFileId;

            await using (var uploadFileStream = file.OpenReadStream())
            {
                storedFileId = await _scanResultService.StoreFile(file.FileName, uploadFileStream);
            }

            await _scanResultService.QueueUrlScan(result, Url.Action("Index", "Download", new {id = storedFileId},
                Request?.Scheme, Request?.Host.Value));

            return CreatedAtAction("Index", "ScanResults", new {id = result.Id}, result);
        }

        /// <summary>
        /// Queue URL for scanning.
        /// </summary>
        /// <param name="url">URL from form data.</param>
        [HttpPost("url")]
        [ProducesResponseType(typeof(ScanResult), StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> ScanUrl(
            [FromForm] [Required] [IsHttpUrl] string url)
        {
            var result = await _scanResultService.CreateScanResult();

            await _scanResultService.QueueUrlScan(result, url);

            return CreatedAtAction("Index", "ScanResults", new {id = result.Id}, result);
        }
    }
}